package edu.njust.underwater.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.njust.underwater.common.Result;
import edu.njust.underwater.exception.ResponseException;
import edu.njust.underwater.mapper.UserMapper;
import edu.njust.underwater.pojo.User;
import edu.njust.underwater.pojo.dto.UserDto;
import edu.njust.underwater.service.UserService;
import edu.njust.underwater.utils.ContextUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

/**
 * @author Goal
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-12-24 21:35:26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public Result checkLogin(User user, HttpSession session) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(User::getPassword, user.getPassword())
                .eq(User::getEmail, user.getEmail());

        User one = this.getOne(wrapper);

        if (one == null) {
            throw new ResponseException("用户名和密码不一致");
        }

//        ContextUtils.setUser(one);

        UserDto userDto = new UserDto();
        userDto.setId(one.getId());
        userDto.setName(one.getName());

        session.setAttribute("user", one);

        return Result.success(userDto);
    }

    @Override
    public Result register(User user, HttpSession session) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        if (this.getOne(wrapper.eq(User::getEmail, user.getEmail())) != null) {
            throw new ResponseException("当前邮箱已被注册");
        }

        this.save(user);

        UserDto userDto = new UserDto();
        userDto.setId(user.getId());
        userDto.setName(user.getName());

        session.setAttribute("user", user);

        return Result.success(userDto);
    }

}
